package com.yikome.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UrlUtils {

    public static byte[] getUrlContent(String urlStr) {
        byte[] bytes = new byte[0];
        if (StrUtil.isEmpty(urlStr)) {
            return bytes;
        }
        HttpURLConnection conn = null;
        try {
            for (int i = 0; i < 2; i++) {
                URL url = new URL(StrUtil.prependIfMissing(urlStr, "https:", "https"));
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(10000);
                int state = conn.getResponseCode();
                if (state == 200) {
                    return readInputStream(conn.getInputStream());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
        	conn.disconnect();
        }
        return bytes;
    }

    public static byte[] readInputStream(InputStream in) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] bytes = new byte[0];
        try {
            byte[] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
            bytes = out.toByteArray();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
        	try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return bytes;
    }
}
